<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var objArr = [
        { id: 11, name: "jack", pid: "" },
        { id: 12, name: "tom", pid: "" },
        { id: 13, name: "rose", pid: "11" },
        { id: 14, name: "lucy", pid: "" },
        { id: 15, name: "lily", pid: "12" }
      ];
      /* 封装一个递归函数 */
      function tool(list, rootValue) {
        var arr = [];
        list.forEach(item => {
          /* 
            pid  有值：说明可能是子children  =====有父亲
            pid  没有值：说明：没有父亲  那他就是根 = 祖先 他就可能有后代    
                他不可能是别人的children  别人只可能是他的children
             */
          if (item.pid == rootValue) {
            // debugger;
            //找到所有的祖先   [{ id: 11, name: "jack", pid: "" },]  返回值： [{ id: 13, name: "rose", pid: "11" },]
            const children = tool(list, item.id); //获取满足id和pid相同的元素对象
            // children有长度 表示这里有子children
            if (children.length) {
              item.children = children; //  当前每一项添加children属性
            }
            arr.push(item); //  将满足的添加到数组中
          }
        });
        return arr;
      }

      var qq = tool(objArr, "");
      console.log(qq, 888);

      /* ====最后的结果 
        var  objArr=[
            {id:11,name:'jack',pid:'',children:[
                {id:13,name:'rose',pid:'11',children:[
                    {id:16,name:'lily',pid:'13'}
                ]}
            ]},
            {id:12,name:'tom',pid:'',children:[
                {id:15,name:'lily',pid:'12'}
            ]},
            {id:14,name:'lucy',pid:''},
        ]
         */
    </script>
  </body>
</html>
